# -*- coding: utf-8 -*-

import json
from public_util.util.AutoUrl import Route
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from package.models import Project, Handle


@Route()
def project(request):
    """项目CRUD接口"""
    if request.method == "GET":
        req = request.REQUEST.get
        init = req("init", 0)
        if init:
            return render_to_response("project/project_index.html", locals())
        else:
            state_type = Project.STATE_TYPE
            project_objs = Project.filter_project(request)
            item_list = []
            for obj in project_objs:
                ver_count = 0
                for b in obj.branch_set.all():
                    ver_count += b.version_set.count()
                item_list.append([obj.pro_name, obj.pro_tag, obj.branch_set.count(),
                                  ver_count, obj.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                                  obj.get_state_display(), obj.id])
            return HttpResponse(json.dumps({"aaData": item_list}), content_type="application/json")
    elif request.method == "POST":
        err_msg = ""
        params = request.post_dic
        p_id = request.GET.get("id", 0)
        handle_info = {
            "user_id": request.admin.id,
            "user": request.admin.alias,
            "pro_name": params.get("pro_name", "")
        }
        if p_id:
            try:
                Handle.create_handle(ope_id=8, **handle_info)
                Project.objects.filter(id=p_id).update(**params)
            except Exception as e:
                err_msg = e
        else:
            try:
                Handle.create_handle(ope_id=7, **handle_info)
                Project(**params).save()
            except Exception as e:
                err_msg = e
        return render_to_response("feedback.html", locals())


@Route()
def project_detail(request):
    """项目详情页面接口"""
    state_type = Project.STATE_TYPE
    p_id = request.REQUEST.get("id", 0)
    if p_id:
        model = Project.objects.filter(id=p_id).first()
    return render_to_response("project/project_detail.html", locals())
